package study.springboot.mvc.client;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
@Component
public class TeacherInfoClient {

    private static String HOST = "http://gateway.staff.xdf.cn";

    private static String PATH = "/teacher/api/v1/teacher_code/page_simple_list";

    private String appId = "AAAfull-teaching-webAAA";
    private String key = "AAAa88306bccde0cd8903a78504846fbcbeAAA";

    @Autowired
    private RestTemplate restTemplate;

    public PageInfo get(String schoolId, int pageNo, int pageSize) {

        //
        Map<String, Object> params = Maps.newHashMap();
        params.put("schoolId", schoolId);
        params.put("pageNo", pageNo);
        params.put("pageSize", pageSize);
        //
        String tt = PATH + "?" + MapUtil.join(params, "&", "=");
        //
        HttpHeaders headers = new HttpHeaders();
        headers.add("appId", StrUtil.removeAll(appId, "A"));
        headers.add("sign", DigestUtil.hmac(HmacAlgorithm.HmacSHA1, StrUtil.removeAll(key, "A").getBytes()).digestBase64(tt, false));
        HttpEntity<?> reqEntity = new HttpEntity(headers);
        ResponseEntity<Response> respEntity = restTemplate.exchange(HOST + tt, HttpMethod.GET, reqEntity, Response.class);

        //log.info("{}", JSONUtil.toJsonPrettyStr(respEntity.getBody()));

        return respEntity.getBody().getData();
    }

    @Data
    public static class Response {
        private String status;
        private String msg;
        private PageInfo data;
    }
}
